package framework.base;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import framework.Page;

public abstract class BaseIbatis3Dao<E> extends SqlSessionDaoSupport implements IBaseDao<E> {
	@Resource
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		super.setSqlSessionFactory(sqlSessionFactory);
	}

	public static final String SPLIT = ".";
	public static final String SQL_INSERT = "insert";
	public static final String SQL_UPDATE = "update";
	public static final String SQL_DELETE = "delete";
	public static final String SQL_SELECTLIST_COUNT = "selectList.count";
	public static final String SQL_SELECTLIST = "selectList";
	public static final String SQL_SELECTONE = "selectOne";
	public static final String SQL_EXPORT = "export";

	@SuppressWarnings("unchecked")
	public E selectOne(Object ob) {
		return (E) getSqlSession().selectOne(getEntityNameSpace(SQL_SELECTONE), ob);
	}

	@SuppressWarnings("unchecked")
	public List<E> selectList(Object ob, Page page) {
		if (page == null) {
			return (List<E>) getSqlSession().selectList(getEntityNameSpace(SQL_SELECTLIST), ob);
		}
		return (List<E>) getSqlSession().selectList(getEntityNameSpace(SQL_SELECTLIST), ob, page.getRowBounds());

	}

	public Object insert(E entity) {
		return getSqlSession().insert(getEntityNameSpace(SQL_INSERT), entity);
	}
	
	public Object delete(E entity){
		return getSqlSession().delete(getEntityNameSpace(SQL_DELETE), entity);
	}
	public Integer delete(List<E> list)
	{
		return delete(getEntityNameSpace(SQL_DELETE), list);
	}
	public Integer delete(String statement, List<E> list)
	{
		int count = 0;
		for (E entity : list)
			count += getSqlSession().delete(statement, entity);

		return count;
	}
	
	public Integer selectCount(Object object)
	{
		return selectCount(getEntityNameSpace(SQL_SELECTLIST_COUNT), object);
	}
	
	public Integer selectCount(String statement, Object object)
	{
		return (Integer)getSqlSession().selectOne(statement, object);
	}
	
	public Object update(E entity) {
		return getSqlSession().insert(getEntityNameSpace(SQL_UPDATE), entity);
	}

	public String getEntityNameSpace(String action) {
		return getEntityClass().getSimpleName() + SPLIT + action;
	}
}
